<?php
return function() {
    $ret = [
        'error' => 0,
        'msg' => '',
        'id' => 0
    ];

    if (!isset($_SESSION['user']) || !$_SESSION['user'] || !isset($_SESSION['user_id']) || !$_SESSION['user_id']) {
        $ret['error'] = 1;
        $ret['msg'] = '请先登录后再发表留言！';
        $this->send($ret);
        return;
    }

    $content = isset($_POST['msg']) ? $_POST['msg'] : '';
    
    if (empty($content)) {
        $ret['error'] = 1;
        $ret['msg'] = '留言内容不能为空！';
        $this->send($ret);
        return;
    }

    $content = htmlentities($content);
    $content = str_replace("\n", "<br/>", $content);

    $timestamp = time();
    $sql = "SELECT id FROM message WHERE user_id=%d AND content='%s' AND created_at>${timestamp}-300";
    if ($this->mysql->query($sql, $_SESSION['user_id'], $content)) {
        $ret['error'] = 1;
        $ret['msg'] = '请不要发表重复留言！';
        $this->send($ret);
        return;
    }

    $sql = "SELECT id FROM message WHERE user_id=%d AND created_at>${timestamp}-300";
    if ($this->mysql->query($sql, $_SESSION['user_id'], $content)) {
        $ret['error'] = 1;
        $ret['msg'] = '您发表留言的频率过于频繁，请等待10分钟后再尝试发表留言！';
        $this->send($ret);
        return;
    }

    $sql = "INSERT INTO message(user_id, content, created_at, updated_at) VALUES(%d, '%s', %d, %d)";
    if ($this->mysql->exec($sql, $_SESSION['user_id'], $content, $timestamp, $timestamp)) {
        $ret['msg'] = '留言成功。';
        $ret['id'] = $this->mysql->lastInsertId();
    } else {
        $ret['error'] = 1;
        $ret['msg'] = '留言失败！';
    }
    $this->send($ret);
};